<template>
  <div class="pc-upload-container">
    <!-- 返回按钮和标题 -->
    <div class="header">
      <el-button :icon="ArrowLeft" @click="onClickLeft" class="back-btn"></el-button>
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/category/' }">文物主体管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{
          path: '/mainpage/',
          query: {
            categoryid: formData.culturalRelic.category_id,
            categoryname: formData.culturalRelic.category_name
          }
        }">{{ formData.culturalRelic.category_name }}</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '#' }" @click.native.prevent="goTodetail">
          {{ formData.culturalRelic.name }}
        </el-breadcrumb-item>
        <el-breadcrumb-item>编辑文物详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div v-if="loading" class="loading-state">
      <div class="loading-text">加载中...</div>
    </div>

    <div v-else-if="error" class="error-state">
      <el-empty description="加载失败，请重试" image="error">
        <template #bottom>
          <el-button type="primary" @click="fetchRelicData">重试</el-button>
        </template>
      </el-empty>
    </div>

    <el-form v-else ref="formRef" :model="formData.culturalRelic" label-width="140px" class="edit-form">
      <!-- 基本信息 -->
      <el-card class="form-card">
        <template #header>基本信息</template>

        <el-form-item label="名称" prop="name" class="name-field-item"
          :rules="[{ required: true, message: '请输入名称', trigger: ['blur', 'change'] }]">
          <el-input v-model="formData.culturalRelic.name" placeholder="请输入文物名称" />
        </el-form-item>

        <el-form-item label="主图" prop="image" class="name-field-item">
          <div class="image-upload-container">
            <!-- 预览区域 -->
            <div v-if="currentRelic.image && !imageChanged.value" class="image-preview">
              <el-image :src="currentRelic.image_base64 || currentRelic.image" fit="cover" class="preview-image" />
            </div>

            <!-- 上传区域 -->
            <el-upload class="upload-component" v-model:file-list="formData.culturalRelic.image"
              list-type="picture-card" :auto-upload="false" :limit="1">
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="彩画做法" prop="painting_technique" class="name-field-item"
          :rules="[{ required: true, message: '请输入具体的彩画做法', trigger: 'blur' }]">
          <el-input v-model="formData.culturalRelic.painting_technique" type="textarea" :rows="4"
            placeholder="请输入具体的彩画做法，例如：仪门月梁侧面两端雕龙凤等吉祥图案，中部则雕刻戏曲人物。" />
        </el-form-item>
      </el-card>

      <!-- 艺术特征 -->
      <el-card class="form-card">
        <template #header>艺术特征</template>

        <el-form-item label="纹样类型" prop="pattern_types" class="name-field-item"
          :rules="[{ required: true, message: '请至少选择一个纹样类型', trigger: 'change', type: 'array' }]">
          <el-checkbox-group v-model="formData.culturalRelic.pattern_types">
            <el-checkbox label="几何纹">几何纹</el-checkbox>
            <el-checkbox label="花卉纹">花卉纹</el-checkbox>
            <el-checkbox label="动物纹">动物纹</el-checkbox>
            <el-checkbox label="人物故事">人物故事</el-checkbox>
            <el-checkbox label="山水">山水</el-checkbox>
            <el-checkbox label="文字">文字</el-checkbox>
            <el-checkbox label="宗教符号">宗教符号</el-checkbox>
            <el-checkbox label="植物纹">植物纹</el-checkbox>
            <el-checkbox label="石雕纹样">石雕纹样</el-checkbox>
            <el-checkbox label="螭龙纹">螭龙纹</el-checkbox>
            <el-checkbox label="卷草纹">卷草纹</el-checkbox>
            <el-checkbox label="麒麟">麒麟</el-checkbox>
            <el-checkbox label="凤凰">凤凰</el-checkbox>
            <el-checkbox label="other">其他</el-checkbox>
          </el-checkbox-group>
          <el-input v-if="formData.culturalRelic.pattern_types.includes('other')"
            v-model="formData.culturalRelic.other_pattern_types" placeholder="请输入其他纹样类型" class="other-input" />
        </el-form-item>

        <el-form-item label="彩画主题" prop="painting_theme" class="name-field-item"
          :rules="[{ required: true, message: '请输入彩画主题', trigger: ['blur', 'change'] }]">
          <el-input v-model="formData.culturalRelic.painting_theme" placeholder="如“龙凤呈祥”“缠枝莲纹”等" />
        </el-form-item>

        <el-form-item label="构图形式" prop="composition_style" class="name-field-item"
          :rules="[{ required: true, message: '请至少选择一个构图形式', trigger: 'change', type: 'array' }]">
          <el-checkbox-group v-model="formData.culturalRelic.composition_style">
            <el-checkbox label="对称式">对称式</el-checkbox>
            <el-checkbox label="自由式">自由式</el-checkbox>
            <el-checkbox label="分段式">分段式</el-checkbox>
            <el-checkbox label="other">其他</el-checkbox>
          </el-checkbox-group>
          <el-input v-if="formData.culturalRelic.composition_style.includes('other')"
            v-model="formData.culturalRelic.other_composition_style" placeholder="请输入其他构图形式" class="other-input" />
        </el-form-item>

        <el-form-item label="主色调" prop="dominant_colors" class="name-field-item"
          :rules="[{ required: true, message: '请至少选择一个主色调', trigger: 'change', type: 'array' }]">
          <el-checkbox-group v-model="formData.culturalRelic.dominant_colors">
            <el-checkbox label="蓝">蓝</el-checkbox>
            <el-checkbox label="绿">绿</el-checkbox>
            <el-checkbox label="红">红</el-checkbox>
            <el-checkbox label="浅绿">浅绿</el-checkbox>
            <el-checkbox label="黄">黄</el-checkbox>
            <el-checkbox label="黑">黑</el-checkbox>
            <el-checkbox label="地仗">地仗</el-checkbox>
            <el-checkbox label="褐色">褐色</el-checkbox>
            <el-checkbox label="金">金</el-checkbox>
            <el-checkbox label="深蓝">深蓝</el-checkbox>
            <el-checkbox label="紫色">紫色</el-checkbox>
            <el-checkbox label="other">其他</el-checkbox>
          </el-checkbox-group>
          <el-input v-if="formData.culturalRelic.dominant_colors.includes('other')"
            v-model="formData.culturalRelic.other_dominant_colors" placeholder="请输入其他主色调" class="other-input" />
        </el-form-item>
      </el-card>

      <!-- 病害情况 -->
      <el-card class="form-card">
        <template #header>病害情况</template>
        <el-form-item label="病害类型" prop="disease_types" class="name-field-item"
          :rules="[{ required: true, message: '请至少选择一个病害情况', trigger: 'change', type: 'array' }]">
          <el-checkbox-group v-model="formData.culturalRelic.disease_types">
            <el-checkbox label="裂隙">裂隙</el-checkbox>
            <el-checkbox label="龟裂">龟裂</el-checkbox>
            <el-checkbox label="起翘">起翘</el-checkbox>
            <el-checkbox label="酥解">酥解</el-checkbox>
            <el-checkbox label="空鼓">空鼓</el-checkbox>
            <el-checkbox label="剥离">剥离</el-checkbox>
            <el-checkbox label="地仗脱落">地仗脱落</el-checkbox>
            <el-checkbox label="颜料剥落">颜料剥落</el-checkbox>
            <el-checkbox label="金层剥落">金层剥落</el-checkbox>
            <el-checkbox label="粉化">粉化</el-checkbox>
            <el-checkbox label="变色">变色</el-checkbox>
            <el-checkbox label="积尘">积尘</el-checkbox>
            <el-checkbox label="结垢">结垢</el-checkbox>
            <el-checkbox label="油烟污损">油烟污损</el-checkbox>
            <el-checkbox label="动物损害">动物损害</el-checkbox>
            <el-checkbox label="水渍">水渍</el-checkbox>
            <el-checkbox label="微生物损害">微生物损害</el-checkbox>
            <el-checkbox label="人为污染">人为污染（刻画/涂鸦/附加管线/钉子等）</el-checkbox>
            <div v-if="formData.culturalRelic.disease_types.includes('人为污染')">
              <el-input v-model="formData.culturalRelic.human_pollution_details" placeholder="请详细描述人为污染情况"
                class="other-input" />
            </div>
            <el-checkbox label="其他污染">其他污染（油漆/涂料/沥青/石灰等）</el-checkbox>
            <div v-if="formData.culturalRelic.disease_types.includes('其他污染')">
              <el-input v-model="formData.culturalRelic.other_pollution_details" placeholder="请详细描述其他污染情况"
                class="other-input" />
            </div>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="病害程度" prop="disease_severity" class="name-field-item"
          :rules="[{ required: true, message: '请选择病害程度', trigger: 'change' }]">
          <el-radio-group v-model="formData.culturalRelic.disease_severity" style="width: 100%;">
            <el-radio label="轻微" style="display: block; margin: 5px 0;">轻微（&lt;10%）</el-radio>
            <el-radio label="中度" style="display: block; margin: 5px 0;">中度（10%-50%）</el-radio>
            <el-radio label="严重" style="display: block; margin: 5px 0;">严重（&gt;50%）</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-card>

      <!-- 现状与残损情况 -->
      <el-card class="form-card">
        <template #header>现状与残损情况</template>
        <el-form-item label="情况描述" prop="current_damage_status" class="name-field-item"
          :rules="[{ required: true, message: '请输入现状描述', trigger: ['blur', 'change'] }]">
          <el-input v-model="formData.culturalRelic.current_damage_status" type="textarea" :rows="4"
            placeholder="描述当前文物的残损部位及状态" />
        </el-form-item>

        <el-form-item label="图像" class="name-field-item">
          <!-- 使用一个外层 div 控制布局 -->
          <div style="display: flex; flex-direction: column; gap: 10px; width: 100%">
            <!-- 添加图片按钮 -->
            <el-button type="primary" size="small" @click="openAddImageDialog" style="width: 15%;">
              <el-icon>
                <Plus />
              </el-icon>
              添加图片
            </el-button>

            <!-- 已上传图片列表 -->
            <el-table :data="formData.culturalRelic.disease_image"
              v-if="formData.culturalRelic.disease_image.length > 0" style="width: 100%; margin-top: 5px;"
              :default-expand-all="false" :border="true" :row-style="{ height: '140px' }"
              :cell-style="{ padding: '10px' }">
              <!-- 图片列 -->
              <el-table-column label="图片" width="250" align="center">
                <template #default="{ row }">
                  <div style="display: flex; justify-content: center;">
                    <div class="image-wrapper"
                      style="width: 160px; height: 120px; overflow: hidden; border-radius: 4px;">
                      <el-image :src="row.url" fit="contain"
                        style="width: 100%; height: 100%; background-color: #f0f0f0;" />
                    </div>
                  </div>
                </template>
              </el-table-column>

              <!-- 信息列 -->
              <el-table-column label="名称" align="center">
                <template #default="{ row }">
                  <div>{{ row.image_name || '未命名' }}</div>
                </template>
              </el-table-column>
              <el-table-column label="描述" align="center">
                <template #default="{ row }">
                  <div>{{ row.description || '无描述' }}</div>
                </template>
              </el-table-column>
              <el-table-column label="上传时间" align="center">
                <template #default="{ row }">
                  <div>{{ row.created_at || "" }}</div>
                </template>
              </el-table-column>

              <!-- 操作列 -->
              <el-table-column label="操作" width="100" align="center" fixed="right">
                <template #default="scope">
                  <div class="operation-btn-group1">
                    <div>
                      <el-button type="primary" :icon="Edit" size="small" @click="editImage(scope.$index, scope.row.id)"
                        class="operation-btn">编辑</el-button>
                    </div>
                    <div style="color: red; font-size: 12px;">
                      <!-- 调试信息：row.id={{ scope.row.id }}，index={{ scope.$index }} -->
                    </div>
                    <div style="margin-top: 10px;">
                      <el-button type="danger" :icon="Delete" size="small"
                        @click="handleDeleteImage(currentRelic.id, scope.row.id)" class="operation-btn">删除</el-button>
                    </div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 添加/编辑图片对话框 -->
          <el-dialog v-model="imageDialogVisible" :title="isEditing ? '修改图像与描述' : '添加图像与描述'" width="500px"
            @close="resetDialog" class="dialog-form">
            <el-form :model="tempImage" label-width="80px" ref="imageFormRef">
              <!-- 图片上传 -->
              <el-form-item label="图片" required>
                <el-upload v-model:file-list="tempImage.fileList" list-type="picture-card"
                  :on-preview="handleTempPreview" :on-remove="handleTempRemove" :on-change="handleTempChange"
                  :auto-upload="false" :limit="1" :on-exceed="() => { }"
                  prop="fileList"
                  :rules="[{ required: true, message: '请上传图片', trigger: ['blur', 'change'] }]">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
              </el-form-item>

              <!-- 名称 -->
              <el-form-item label="名称" prop="customName" placeholder="如：戏台藻井东"
                :rules="[{ required: true, message: '请输入图片名称', trigger: ['blur', 'change'] }]">
                <el-input v-model="tempImage.customName" />
              </el-form-item>

              <!-- 描述 -->
              <el-form-item label="描述">
                <el-input v-model="tempImage.description" type="textarea" :rows="3" placeholder="如：位于东墙中部，长约30cm" />
              </el-form-item>
            </el-form>

            <!-- 对话框底部按钮 -->
            <template #footer>
              <el-button @click="imageDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="confirmImage">确认</el-button>
            </template>
          </el-dialog>
        </el-form-item>
      </el-card>

      <!-- 光谱与三维数据 -->
      <el-card class="form-card">
        <template #header>光谱与三维数据</template>

        <el-form-item label="是否采集光谱图像" prop="hasSpectrum"
          :rules="[{ required: false, message: '请选择是否有光谱图像', trigger: ['blur', 'change'] }]">
          <el-radio-group v-model="formData.culturalRelic.hasSpectrum">
            <el-radio :label="'true'">是</el-radio>
            <el-radio :label="'false'">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="光谱数据文件" v-if="formData.culturalRelic.hasSpectrum === 'true'" prop="spectrum_file"
          :rules="[{ required: false, message: '请上传光谱数据文件', trigger: ['blur', 'change'] }]">
          <!-- 显示旧文件名 -->
          <div v-if="currentRelic.spectrum_file_name" class="file-info">
            <el-icon>
              <Files />
            </el-icon>
            <span>{{ currentRelic.spectrum_file_name }}</span>
          </div>
          <!-- 上传新文件 -->
          <el-upload v-model:file-list="formData.culturalRelic.spectrum_file" :auto-upload="false" :limit="1">
            <el-button type="primary">上传文件</el-button>
          </el-upload>
        </el-form-item>

        <el-form-item label="是否采集三维图像" prop="hasThreeD"
          :rules="[{ required: false, message: '请选择是否采集三维图像', trigger: ['blur', 'change'] }]">
          <el-radio-group v-model="formData.culturalRelic.hasThreeD">
            <el-radio :label="'true'">是</el-radio>
            <el-radio :label="'false'">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="三维数据文件" v-if="formData.culturalRelic.hasThreeD === 'true'" prop="threeD_file"
          :rules="[{ required: false, message: '请上传三维数据文件', trigger: ['blur', 'change'] }]">
          <!-- 显示旧文件名 -->
          <div v-if="currentRelic.threeD_file_name" class="file-info">
            <el-icon>
              <Files />
            </el-icon>
            <span>{{ currentRelic.threeD_file_name }}</span>
          </div>
          <!-- 上传新文件 -->
          <el-upload v-model:file-list="formData.culturalRelic.threeD_file" :auto-upload="false" :limit="1">
            <el-button type="primary">上传文件</el-button>
          </el-upload>
        </el-form-item>
      </el-card>

      <!-- 提交按钮 -->
      <div class="form-actions">
        <el-button type="primary" @click="handleSubmit" :loading="loading">保存修改</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { useEdit } from '@/components/composables/useEdit'
import { showToastMessage } from '@/utils/message'
import { ArrowLeft, ArrowRight, Plus, Files, Delete, Edit } from '@element-plus/icons-vue'
import { number } from 'echarts'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const {
  loading,
  error,
  currentRelic,
  formRef,
  formData,
  imageChanged,
  goTodetail,
  fetchRelicData,
  onClickLeft,
  onSubmit,
  handleCancel,
  handleDeleteImage,
} = useEdit()

const handleSubmit = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      onSubmit()
    } else {
      onFailed()
    }
  })
}

const onFailed = () => {
  showToastMessage("error", "请完善必填信息")
}

// 图片对话框控制
const imageDialogVisible = ref(false)
const tempPreviewVisible = ref(false)
const tempPreviewUrl = ref('')

// 临时图片数据（用于对话框表单）
const tempImage = ref({
  fileList: [] as any[],
  customName: '',
  description: '',
  url: '',
  uid: '',
  id: number
})

// 是否处于编辑模式
const isEditing = ref(false)
const editingIndex = ref(-1)

// 表单引用（用于校验）
const imageFormRef = ref()

// 打开添加图片对话框
const openAddImageDialog = () => {
  isEditing.value = false
  editingIndex.value = -1
  resetDialog()
  imageDialogVisible.value = true
}

// 编辑已有图片
const editImage = (index: number, image_id: number) => {
  const file = formData.culturalRelic.disease_image[index]
  tempImage.value.fileList = [file]
  tempImage.value.customName = file.image_name || ''
  tempImage.value.description = file.description || ''
  tempImage.value.url = file.url
  tempImage.value.id = file.id
  isEditing.value = true
  editingIndex.value = index
  imageDialogVisible.value = true
}

// 重置对话框表单
const resetDialog = () => {
  tempImage.value = {
    fileList: [],
    customName: '',
    description: '',
    url: '',
    uid: '',
  }
}

// 临时上传处理
const handleTempChange = (file: any, fileList: any[]) => {
  tempImage.value.fileList = fileList.slice(-1) // 限制一张
  tempImage.value.url = file.url
  tempImage.value.uid = file.uid
}

const handleTempRemove = () => {
  tempImage.value.fileList = []
  tempImage.value.url = ''
}

const handleTempPreview = (file: any) => {
  tempPreviewUrl.value = file.url
  tempPreviewVisible.value = true
}

// 确认上传或修改
const confirmImage = () => {
  if (!tempImage.value.url) {
    ElMessage.error('请先上传图片')
    return
  }
  if (!tempImage.value.customName.trim()) {
    ElMessage.error('请输入图片名称')
    return
  }
  const rawFile = tempImage.value.fileList[0]?.raw
  const imageObj = {
    id: tempImage.value.id,
    file: rawFile,
    image: rawFile ? rawFile.name : 'edited-image.jpg',
    url: tempImage.value.url,
    image_name: tempImage.value.customName,
    description: tempImage.value.description,
  }

  if (isEditing.value && editingIndex.value !== -1) {
    // 修改模式：保留原始文件（如果没有新文件，则使用旧的 file）
    const oldFileObj = formData.culturalRelic.disease_image[editingIndex.value]
    imageObj.file = rawFile || oldFileObj.file
    formData.culturalRelic.disease_image.splice(editingIndex.value, 1, imageObj)
  } else {
    // 新增：必须有 rawFile
    if (!rawFile) {
      ElMessage.error('请上传图片文件')
      return
    }
    formData.culturalRelic.disease_image.push(imageObj)
  }

  imageDialogVisible.value = false
  ElMessage.success(isEditing.value ? '修改成功' : '添加成功')
}

</script>

<style scoped>
/* 样式同前，略 */
.pc-upload-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.back-btn {
  margin-right: 15px;
}

.title {
  margin: 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.edit-form {
  max-width: 900px;
  margin: 0 auto;
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.el-card__header {
  background-color: #f5f7fa;
  font-size: 16px;
  font-weight: 500;
}

.other-input {
  margin-top: 15px;
  width: 300px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  margin-bottom: 50px;
}

.el-radio-group,
.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px 30px;
  margin-top: 5px;
}

.el-upload {
  margin-top: 5px;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.upload-component {
  margin-top: 0;
}

.image-upload-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.dialog-form .el-form-item {
  margin-bottom: 16px;
  /* 可根据需要调整间距，如 12px、20px 等 */
}

/* 设置整个文件信息区域的基本样式 */
.file-info {
  display: flex;
  align-items: center;
  /* 垂直居中图标和文本 */
  padding: 8px;
  background-color: #f0f2f5;
  /* 背景颜色 */
  border-radius: 4px;
  max-width: 300px;
  /* 根据实际需要调整最大宽度 */
  word-break: break-all;
  /* 当遇到长单词或URL时自动换行 */
}

/* 设置图标样式 */
.file-info .el-icon {
  margin-right: 8px;
  /* 图标与文字之间的间距 */
}

/* 设置文件名样式 */
.filename {
  flex-grow: 1;
  /* 让文件名占据剩余空间 */
  overflow: hidden;
  /* 隐藏超出部分 */
  text-overflow: ellipsis;
  /* 当文本溢出时显示省略号 */
  white-space: nowrap;
  /* 禁止文本换行 */
}

:deep(.name-field-item .el-form-item__content) {
  margin-left: 1px !important;
  /* 调整与 label 的间距 */
}

/* 或者整体左移 */
.name-field-item {
  margin-left: -50px;
}
</style>
